package com.dgt.trade.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dgt.trade.entitys.User;
import com.dgt.trade.entitys.UserBalance;
import com.dgt.trade.service.IUserService;
import com.dgt.trade.service.UserBalanceService;
import com.dgt.trade.utils.*;
import com.dgt.trade.utils.config.SwiftpassConfig;
import com.dgt.trade.utils.config.UrlByCfg;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PayController extends BaseController {
    private static Map<String, String> orderResult = new HashMap<String, String>(); //用来存储订单的交易状态(key:订单号，value:状态(0:未支付，1：已支付))  ---- 这里可以根据需要存储在数据库中
    private static Map<String, Object> entityMap = new HashMap<String, Object>();//存放数据库实体Map
    @Autowired
    private IUserService sUserBService;
    @Autowired
    private UserBalanceService sUserBalanceLogService;

    //商品名称
    private String body;
    //价格
    private Float money;
    //用户
    private User sUser;
    //终端ip
    private String ip;

    //兴业银行通知
    @RequestMapping("PayResult.do")
    private void PayResult(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            String resString = XmlUtils.parseRequst(req);
            System.out.println("通知内容：" + resString);
            String respString = "fail";
            if (resString != null && !"".equals(resString)) {
                Map<String, String> map = XmlUtils.toMap(resString.getBytes(), "utf-8");
                String res = XmlUtils.toXml(map);
                System.out.println("通知内容：" + res);
                String out_trade_no = map.get("out_trade_no");
                if (map.containsKey("sign")) {
                    if (!SignUtils.checkParam(map, SwiftpassConfig.key)) {
                        res = "验证签名不通过";
                        respString = "fail";
                    } else {
                        String status = map.get("status");
                        if (status != null && "0".equals(status)) {
                            String result_code = String.valueOf(map.get("result_code"));
                            if (result_code != null && "0".equals(result_code)) {
                                if (orderResult == null) {
                                    orderResult = new HashMap<String, String>();
                                }
                                if (orderResult.containsKey(out_trade_no)) {
                                    orderResult.put(out_trade_no, "1");
                                }
                            }
                        }
                        // 此处可以在添加相关处理业务，校验通知参数中的商户订单号out_trade_no和金额total_fee是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
                        respString = "success";
                        //支付成功 更新数据库账户余额
                        if (String.valueOf(map.get("out_trade_no")) != null && String.valueOf(map.get("out_trade_no")).equals(entityMap.get("out_trade_no")) && String.valueOf(map.get("total_fee")) != null && String.valueOf(map.get("total_fee")).equals(entityMap.get("total_fee"))) {
                            if (sUserBService.iszhifu((Float) entityMap.get("total_fee") / 100,
                                    ((User) entityMap.get("sUser")).getId())) {
                                orderResult.remove(out_trade_no);
                            } else {
                                respString = "fail";
                            }
                        }
                        int i = sUserBalanceLogService.insert(new UserBalance(
                                ((User) entityMap.get("sUser")).getId(),
                                (byte) 1,
                                ((User) entityMap.get("sUser")).getBalance(),
                                (Float) entityMap.get("total_fee") / 100,
                                Integer.parseInt(
                                        "0".equals(orderResult.get("out_trade_no")) ? "256" : "2"),
                                new Date(), "充值"));
                        System.out.println(i);
                    }
                }
            }
            resp.getWriter().write(respString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //中信银行通知
    @RequestMapping("PayResultzxyh.do")
    private void PayResultzxyh(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            String resString = XmlUtils.parseRequst(req);
            System.out.println("通知内容：" + resString);
            String respString = "fail";
            if (resString != null && !"".equals(resString)) {
                Map<String, String> map = XmlUtils.toMap(resString.getBytes(), "utf-8");
                String res = XmlUtils.toXml(map);
                String sign_type = String.valueOf(map.get("sign_type"));
                String reSign = String.valueOf(map.get("sign"));
                String out_trade_no = String.valueOf(map.get("out_trade_no"));
                System.out.println("通知内容：" + res);
                if (map.containsKey("sign")) {
                    if (SignUtil.verifySign(reSign, sign_type, map)) {
                        String status = String.valueOf(map.get("status"));
                        if (status != null && "0".equals(status)) {
                            String result_code = String.valueOf(map.get("result_code"));
                            if (result_code != null && "0".equals(result_code)) {
                                if (orderResult == null) {
                                    orderResult = new HashMap<String, String>();
                                }
                                if (orderResult.containsKey(out_trade_no)) {
                                    orderResult.put(out_trade_no, "1");
                                }
                            }
                        }
                        respString = "success";
                        // 检验通知的订单号，总金额 是否跟本地一样
                        if (String.valueOf(map.get("out_trade_no")) != null && String.valueOf(map.get("out_trade_no")).equals(entityMap.get("out_trade_no")) && String.valueOf(map.get("total_fee")) != null && String.valueOf(map.get("total_fee")).equals(entityMap.get("total_fee"))) {
                            if (sUserBService.iszhifu((Float) entityMap.get("total_fee") / 100,
                                    ((User) entityMap.get("sUser")).getId())) {
                                orderResult.remove(out_trade_no);
                            } else {
                                respString = "fail";
                            }
                        }
                        int i = sUserBalanceLogService.insert(new UserBalance(
                                ((User) entityMap.get("sUser")).getId(), (byte) 1,
                                ((User) entityMap.get("sUser")).getBalance(), (Float) entityMap.get("total_fee") / 100,
                                Integer.parseInt("0".equals(orderResult.get("out_trade_no")) ? "256" : "2"), new Date(),
                                "充值"));
                        System.out.println(i);
                    }
                }
            }
            resp.getWriter().write(respString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //平安银行通知
    @RequestMapping("PayResultjftzy.do")
    private void PayResultjftzy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            String resString = XmlUtils.parseRequst(req);
            System.out.println("通知内容：" + resString);
            String respString = "fail";
            if (resString != null && !"".equals(resString)) {
                Map<String, String> map = JsonRoMap.JsonToMap(resString);
                String order_no = String.valueOf(map.get("order_no"));
                String res = XmlUtils.toXml(map);
                System.out.println("通知内容：" + res);
                if (map.containsKey("sign")) {
                    if (!SignUtils.checkParam(map, SwiftpassConfig.jftkey)) {
                        res = "验证签名不通过";
                        respString = "fail";
                    } else {
                        // 此处可以在添加相关处理业务，校验通知参数中的商户订单号和金额是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
                        respString = "success";
                        if (orderResult == null) {
                            orderResult = new HashMap<String, String>();
                        }
                        if (orderResult.containsKey(order_no)) {
                            orderResult.put(order_no, "1");
                        }
                        if (order_no != null && order_no.equals(entityMap.get("payment_id")) && String.valueOf(map.get("money")) != null && String.valueOf(map.get("money")).equals(entityMap.get("money"))) {
                            //如果通知返回支付成功
                            if (String.valueOf(map.get("status")) != null && "1".equals(orderResult.get(order_no))) {
                                //更新数据库 增加余额
                                if (sUserBService.iszhifu((Float) entityMap.get("money") / 100,
                                        ((User) entityMap.get("sUser")).getId())) {
                                    orderResult.remove(order_no);
                                }
                            }
                            //添加支付记录
                            int i = sUserBalanceLogService.insert(new UserBalance(
                                    ((User) entityMap.get("sUser")).getId(),
                                    (byte) 1,
                                    ((User) entityMap.get("sUser")).getBalance(),
                                    (Float) entityMap.get("money") / 100,
                                    Integer.parseInt(
                                            "1".equals(orderResult.get("status")) ? "2" : "256"),
                                    new Date(), "充值"));
                            System.out.println(i);
                        }
                    }
                }
            }
            resp.getWriter().write(respString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //环迅支付通知
    @RequestMapping("PayResulthxzfyl.do")
    private void PayResulthxzfyl(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("接收服务端返回：===================");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            // 获取xml
            String resultXml = req.getParameter("paymentResult");
            // 读取配置文件
            Map<String, String> map = UrlByCfg.getParamsByCfg();
            String merCode = String.valueOf(map.get("merCode"));
            String directStr = String.valueOf(map.get("directStr"));
            String ipsRsaPub = String.valueOf(map.get("ipsRsaPub"));
            // 获取请求uri
            String httpInfo = req.getRequestURI();
            if (httpInfo.contains("/merchant/success")) {
                // 支付结果成功返回
                String result = UrlByCfg.returnPaymentPage(resultXml, merCode, directStr, ipsRsaPub);
                req.setAttribute("result", result);
                // 返回相应页面
                //req.getRequestDispatcher("/WEB-INF/views/wsResult.jsp").forward(req, resp);
            } else if (httpInfo.contains("/merchant/s2surl")) {
                // S2S返回
                UrlByCfg.s2sNotify(resultXml, merCode, directStr, ipsRsaPub);
                System.out.println("ipscheckok");
                PrintWriter printer = resp.getWriter();
                printer.write("ipscheckok");
                printer.flush();
                printer.close();
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    //兴业银行微信h5支付
    @RequestMapping("paywxwap.do")
    private String paywxwap(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        String str = new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(1000);
        map.put("mch_id", SwiftpassConfig.mch_id);
        map.put("service", "pay.weixin.wappay");
        map.put("body", body);
        map.put("total_fee", String.valueOf(money));
        // 要改成用户
        entityMap.put("sUser", sUser);
        // 要改成充值金额 单位一分 类型float
        entityMap.put("total_fee", money);
        // 要改成终端IP 类型String
        map.put("mch_create_ip", ip);
        //如果是用于苹果app应用里值为iOS_SDK；如果是用于安卓app应用里值为AND_SDK；如果是用于手机网站，值为iOS_WAP或AND_WAP均可
        map.put("device_info", "AND_SDK");
        //如果是用于苹果或安卓app应用中，传分别对应在AppStore和安卓分发市场中的应用名（如：王者荣耀）如果是用于手机网站，传对应的网站名(如：京东官网)
        map.put("mch_app_name", "王者荣耀");
        //如果是用于苹果或安卓app应用中，苹果传IOS 应用唯一标识(如：com.tencent.wzryIOS)安卓传包名(如：com.tencent.tmgp.sgame)如果是用于手机网站，传网站首页URL地址,必须保证公网能正常访问(如：https://m.jd.com)
        map.put("mch_app_id", "com.tencent.tmgp.sgame");
        // 订单号
        map.put("out_trade_no", str);
        entityMap.put("out_trade_no", str);
        map.put("notify_url", SwiftpassConfig.notify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + SwiftpassConfig.key, "utf-8");
        map.put("sign", sign);
        String reqUrl = SwiftpassConfig.req_url;
        System.out.println("reqUrl：" + reqUrl);
        System.out.println("reqParams:" + XmlUtils.parseXML(map));
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            // httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                Map<String, String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                res = XmlUtils.toXml(resultMap);
                System.out.println("请求结果：" + res);
                if (resultMap.containsKey("sign")) {
                    if (!SignUtils.checkParam(resultMap, SwiftpassConfig.key)) {
                        res = "验证签名不通过";
                    } else {
                        if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                            if (orderResult == null) {
                                orderResult = new HashMap<String, String>();
                            }
                            orderResult.put(map.get("out_trade_no"), "0");// 初始状态
                            String pay_info = resultMap.get("pay_info");
                            // System.out.println("code_img_url"+code_img_url);
                            req.setAttribute("pay_info", pay_info);
                            req.setAttribute("out_trade_no", map.get("out_trade_no"));
                            req.setAttribute("total_fee", map.get("total_fee"));
                            req.setAttribute("body", map.get("body"));
                            // req.getRequestDispatcher("index-pay-result.jsp").forward(req, resp);
                        } else {
                            req.setAttribute("result", res);
                        }
                    }
                }
            } else {
                res = "操作失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        if (res.startsWith("<")) {
            resp.setHeader("Content-type", "text/xml;charset=UTF-8");
        } else {
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
        }
        resp.getWriter().write(res);
        // }
        return "pay/index-paywxwap-result";
    }

    //兴业银行微信扫码支付 用不了商户未开通
    @RequestMapping("payxyyhwxsm.do")
    private String payxyyhwxsm(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = request.getSession();
        body = (String) session.getAttribute("body");
        money = Float.parseFloat(session.getAttribute("money").toString());
        sUser = (User) session.getAttribute("user");
        ip = (String) session.getAttribute("ip");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        map.put("mch_id", SwiftpassConfig.mch_id);
        map.put("notify_url", SwiftpassConfig.notify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        map.put("service", "pay.weixin.native");
        map.put("out_trade_no", new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(1000));
        map.put("body", body);
        map.put("total_fee", String.valueOf(money));
        map.put("mch_create_ip", ip);
        entityMap.put("sUser", sUser);
        // 要改成充值金额 单位一分 类型float
        entityMap.put("total_fee", 1F);
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + SwiftpassConfig.key, "utf-8");
        map.put("sign", sign);
        String reqUrl = SwiftpassConfig.req_url;
        System.out.println("reqUrl：" + reqUrl);
        System.out.println("reqParams:" + XmlUtils.parseXML(map));
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            // httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                Map<String, String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                res = XmlUtils.toXml(resultMap);
                System.out.println("请求结果：" + res);

                if (resultMap.containsKey("sign")) {
                    if (!SignUtils.checkParam(resultMap, SwiftpassConfig.key)) {
                        res = "验证签名不通过";
                    } else {
                        if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                            if (orderResult == null) {
                                orderResult = new HashMap<String, String>();
                            }
                            orderResult.put(map.get("out_trade_no"), "0");// 初始状态

                            String code_img_url = resultMap.get("code_img_url");
                            // System.out.println("code_img_url"+code_img_url);
                            req.setAttribute("code_img_url", code_img_url);
                            req.setAttribute("out_trade_no", map.get("out_trade_no"));
                            req.setAttribute("total_fee", map.get("total_fee"));
                            req.setAttribute("body", map.get("body"));
                            //req.getRequestDispatcher("index-pay-result.jsp").forward(req, resp);
                        } else {
                            req.setAttribute("result", res);
                        }
                    }
                }
            } else {
                res = "操作失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        if (res.startsWith("<")) {
            resp.setHeader("Content-type", "text/xml;charset=UTF-8");
        } else {
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
        }
        resp.getWriter().write(res);
        return "pay/index-payxyyhwxsm-result";
    }

    //平安银行京东 √
    @RequestMapping("payjftjd.do")
    private String payjftjd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = request.getSession();
        body = (String) session.getAttribute("body");
        money = Float.parseFloat(session.getAttribute("money").toString());
        sUser = (User) session.getAttribute("user");
        ip = (String) session.getAttribute("ip");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        String str = new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(10000000);
        map.put("version", "2");
        map.put("pay_type", "jd");
        map.put("payment_id", str);
        entityMap.put("payment_id", str);
        //map.put("body", "ceshi");
        map.put("body", body);
        //map.put("money", "1");
        map.put("money", String.valueOf(money));
        //map.put("ip", "127.0.0.1");
        map.put("ip", ip);
        //同步返回地址, 不可空
        map.put("return_url", "http://www.cehk.vip:8082/PayResult.do");
        //异步通知地址, 不可空
        map.put("notify_url", SwiftpassConfig.jftnotify_url);
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        map.put("time", time);
        map.put("user_id", SwiftpassConfig.user_id);
        entityMap.put("sUser", sUser);
        entityMap.put("money", money);
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        System.out.println("要签名的参数:" + preStr);
        String sign = MD5.sign(preStr, "&key=" + SwiftpassConfig.jftkey, "utf-8");
        map.put("sign", sign.toLowerCase());
        map.put("remark", "1");
        StringBuilder buf2 = new StringBuilder((map.size() + 1) * 10);
        SignUtils.buildPayParams(buf2, map, false);
        String preStr2 = buf2.toString();
        System.out.println("签名之后 发送：" + preStr2);
        req.setAttribute("version", map.get("version"));
        req.setAttribute("pay_type", map.get("pay_type"));
        req.setAttribute("payment_id", map.get("payment_id"));
        req.setAttribute("body", map.get("body"));
        req.setAttribute("money", map.get("money"));
        req.setAttribute("ip", map.get("ip"));
        req.setAttribute("return_url", map.get("return_url"));
        req.setAttribute("notify_url", map.get("notify_url"));
        req.setAttribute("time", map.get("time"));
        req.setAttribute("user_id", map.get("user_id"));
        req.setAttribute("sign", map.get("sign"));
        req.setAttribute("remark", map.get("remark"));
        if (orderResult == null) {
            orderResult = new HashMap<String, String>();
        }
        orderResult.put(map.get("payment_id"), "0");// 初始状态
        return "pay/pay";
    }

    //平安银行微信h5支付  域名问题 使用不了
    @RequestMapping("paywxh5.do")
    private String paywxh5(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        String str = new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(1000);
        map.put("version", "2");
        map.put("pay_type", "weixinh5");
        map.put("payment_id", str);
        entityMap.put("payment_id", str);
        map.put("user_id", SwiftpassConfig.user_id);
        entityMap.put("sUser", sUser);
        map.put("money", String.valueOf(money));
        entityMap.put("money", 1F);
        map.put("return_url", "0");
        map.put("notify_url", SwiftpassConfig.jftnotify_url);
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        map.put("time", time);
        //中文乱码 原因未知
        map.put("body", body);
        map.put("ip", ip);
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + SwiftpassConfig.jftkey, "utf-8");
        map.put("sign", sign.toLowerCase());
        map.put("remark", "测试");
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        try {
            HttpPost httpPost = new HttpPost("http://pay.haodbao.com/gateway/h5");
            String s = JsonRoMap.MapToJson(map);
            System.out.println(s);
            StringEntity entityParams = new StringEntity(s);
            httpPost.setEntity(entityParams);
            // httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                String string = EntityUtils.toString(response.getEntity());
                System.out.println(string);
                Map<String, String> resultMap = JsonRoMap.JsonToMap(string);
                if ("1".equals(resultMap.get("status"))) {
                    if (orderResult == null) {
                        orderResult = new HashMap<String, String>();
                    }
                    orderResult.put(map.get("out_trade_no"), "0");// 初始状态
                    String pay_info = resultMap.get("info");
                    // System.out.println("code_img_url"+code_img_url);
                    req.setAttribute("pay_info", pay_info);
                    req.setAttribute("out_trade_no", map.get("payment_id"));
                    req.setAttribute("total_fee", map.get("money"));
                    req.setAttribute("body", map.get("body"));
                    // req.getRequestDispatcher("index-pay-result.jsp").forward(req, resp);
                } else {
                    req.setAttribute("result", res);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        return "pay/index-paywxh5-result";
    }

    //中信银行支付宝扫码
    @RequestMapping("payzfbsm.do")
    private String payzfbsm(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = request.getSession();
        body = (String) session.getAttribute("body");
        money = Float.parseFloat(session.getAttribute("money").toString());
        sUser = (User) session.getAttribute("user");
        ip = (String) session.getAttribute("ip");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        map.put("mch_id", SwiftpassConfig.zxyhmch_id);
        map.put("notify_url", SwiftpassConfig.zxyhnotify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        map.put("service", "pay.alipay.native");
        map.put("mch_create_ip", ip);
        String sign_type = "RSA_1_256";
        map.put("sign_type", sign_type);
        String str = new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(10000000);
        map.put("out_trade_no", str);
        map.put("body", body);
        map.put("total_fee", String.valueOf(money));
        entityMap.put("out_trade_no", str);
        entityMap.put("sUser", sUser);
        entityMap.put("total_fee",  String.valueOf(money));
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        map.put("sign", SignUtil.getSign(sign_type, preStr));
        String reqUrl = SwiftpassConfig.req_url;
        System.out.println("reqParams:" + XmlUtils.parseXML(map));
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        String reSign = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                Map<String, String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                reSign = resultMap.get("sign");
                res = XmlUtils.toXml(resultMap);
                System.out.println("res:" + res);
                if (resultMap.containsKey("sign")) {
                    if (SignUtil.verifySign(reSign, sign_type, resultMap)) {
                        System.out.println("返回参数验证签名通过。。。");
                        if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                            if (orderResult == null) {
                                orderResult = new HashMap<String, String>();
                            }
                            orderResult.put(map.get("out_trade_no"), "0");// 初始状态
                            String code_img_url = resultMap.get("code_img_url");
                            req.setAttribute("code_img_url", code_img_url);
                            req.setAttribute("out_trade_no", map.get("out_trade_no"));
                            req.setAttribute("total_fee", map.get("total_fee"));
                            req.setAttribute("body", map.get("body"));
                            //req.getRequestDispatcher("index-pay-result.jsp").forward(req, resp);
                        } else {
                            req.setAttribute("result", res);
                        }
                    }

                }
            } else {
                res = "操作失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        if (res.startsWith("<")) {
            resp.setHeader("Content-type", "text/xml;charset=UTF-8");
        } else {
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
        }
        resp.getWriter().write(res);
        return "pay/index-payzfbsm-result";
    }

    //中信银行微信扫码
    @RequestMapping("payzxyhwxsm.do")
    private String payzxyhwxsm(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = request.getSession();
        body = (String) session.getAttribute("body");
        money = Float.parseFloat(session.getAttribute("money").toString());
        sUser = (User) session.getAttribute("user");
        ip = (String) session.getAttribute("ip");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        map.put("mch_id", SwiftpassConfig.zxyhmch_id);
        map.put("notify_url", SwiftpassConfig.zxyhnotify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        map.put("service", "pay.weixin.native");
        String sign_type = "RSA_1_256";
        map.put("sign_type", sign_type);
        map.put("body", body);
        map.put("total_fee", String.valueOf(money));
        map.put("mch_create_ip", ip);
        String str = new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(10000000);
        map.put("out_trade_no", str);
        entityMap.put("out_trade_no", str);
        entityMap.put("sUser", sUser);
        entityMap.put("total_fee", money);
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        map.put("sign", SignUtil.getSign(sign_type, preStr));
        String reqUrl = SwiftpassConfig.req_url;
        System.out.println("reqUrl：" + reqUrl);

        System.out.println("reqParams:" + XmlUtils.parseXML(map));
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        String reSign = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                Map<String, String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                reSign = resultMap.get("sign");
                res = XmlUtils.toXml(resultMap);
                System.out.println("签名方式" + sign_type);
                if (resultMap.containsKey("sign")) {
                    if (SignUtil.verifySign(reSign, sign_type, resultMap)) {
                        System.out.println("返回参数验证签名通过。。。");
                        if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                            if (orderResult == null) {
                                orderResult = new HashMap<String, String>();
                            }
                            orderResult.put(map.get("out_trade_no"), "0");// 初始状态

                            String code_img_url = resultMap.get("code_img_url");
                            req.setAttribute("code_img_url", code_img_url);
                            req.setAttribute("out_trade_no", map.get("out_trade_no"));
                            req.setAttribute("total_fee", map.get("total_fee"));
                            req.setAttribute("body", map.get("body"));
                            //req.getRequestDispatcher("index-pay-result.jsp").forward(req, resp);
                        } else {
                            req.setAttribute("result", res);
                        }
                    }

                }
            } else {
                res = "操作失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        if (res.startsWith("<")) {
            resp.setHeader("Content-type", "text/xml;charset=UTF-8");
        } else {
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
        }
        resp.getWriter().write(res);
        return "pay/index-payzxyhwxsm-result";
    }

    //中信银行qq钱包扫码支付
    @RequestMapping("payqqqbsm.do")
    private String payqqqbsm(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = request.getSession();
        body = (String) session.getAttribute("body");
        money = Float.parseFloat(session.getAttribute("money").toString());
        sUser = (User) session.getAttribute("user");
        ip = (String) session.getAttribute("ip");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        map.put("service", "pay.tenpay.native");
        String sign_type = "RSA_1_256";
        map.put("sign_type", sign_type);
        map.put("mch_id", SwiftpassConfig.zxyhmch_id);
        String str = new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(10000000);
        map.put("out_trade_no", str);
        map.put("body", body);
        map.put("total_fee", String.valueOf(money));
        map.put("mch_create_ip", ip);
        map.put("notify_url", SwiftpassConfig.zxyhnotify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        entityMap.put("out_trade_no", str);
        entityMap.put("sUser", sUser);
        entityMap.put("total_fee", money);
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        map.put("sign", SignUtil.getSign(sign_type, preStr));
        String reqUrl = SwiftpassConfig.req_url;
        System.out.println("reqUrl：" + reqUrl);
        System.out.println("reqParams:" + XmlUtils.parseXML(map));
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        String reSign = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                Map<String, String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                res = XmlUtils.toXml(resultMap);
                System.out.println("请求结果：" + res);
                reSign = resultMap.get("sign");
                if (resultMap.containsKey("sign")) {
                    if (!SignUtil.verifySign(reSign, sign_type, resultMap)) {
                        res = "验证签名不通过";
                    } else {
                        if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                            if (orderResult == null) {
                                orderResult = new HashMap<String, String>();
                            }
                            orderResult.put(map.get("out_trade_no"), "0");// 初始状态

                            String code_img_url = resultMap.get("code_img_url");
                            // System.out.println("code_img_url"+code_img_url);
                            req.setAttribute("code_img_url", code_img_url);
                            req.setAttribute("out_trade_no", map.get("out_trade_no"));
                            req.setAttribute("total_fee", map.get("total_fee"));
                            req.setAttribute("body", map.get("body"));
                            //req.getRequestDispatcher("index-pay-result.jsp").forward(req, resp);
                        } else {
                            req.setAttribute("result", res);
                        }
                    }
                }
            } else {
                res = "操作失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        if (res.startsWith("<")) {
            resp.setHeader("Content-type", "text/xml;charset=UTF-8");
        } else {
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
        }
        resp.getWriter().write(res);
        return "pay/index-payqqqbsm-result";
    }

    //环迅支付银联   域名问题 使用不了
    @RequestMapping("payhxzf.do")
    private String payhxzf(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        body = (String) session.getAttribute("body");
        money = Float.parseFloat(session.getAttribute("money").toString());
        sUser = (User) session.getAttribute("user");
        ip = (String) session.getAttribute("ip");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try { // 获取页面请求信息
            Map<String, String> map = UrlByCfg.getUrlByCfg();
            String action = map.get("formAction");

            // body部分
            String bodyXml = "<body>" +
                    "<MerBillNo>" + new SimpleDateFormat("yyyyMMddHHmmssss").format(new Date()) + new Random().nextInt(1000) + "</MerBillNo>" +//商户订单号(*)
                    "<Lang>" + "GB" + "</Lang>" +//语言
                    "<Amount>" + money + "</Amount>" +//订单金额(*)
                    "<Date>" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "</Date>" +//订单日期(*)
                    "<CurrencyType>" + "156" + "</CurrencyType>" +//支付币种(*) 人民币
                    "<GatewayType>" + "01" + "</GatewayType>" +//支持方式(*)
                    "<Merchanturl>" + "http://43.227.216.84:8082/PayResulthxzfyl.do" + "</Merchanturl>" +//支付结果成功返回地址
                    "<FailUrl><![CDATA[" + "https://www.ips.com.cn/ipay/Default.aspx" + "]]></FailUrl>" +//支付结果失败返回地址
                    "<Attach><![CDATA[" + "测试" + "]]></Attach>" +//商户数据包
                    "<OrderEncodeType>" + "5" + "</OrderEncodeType>" +//订单支付加密方式(*) MD5
                    "<RetEncodeType>" + "17" + "</RetEncodeType>" +//交易返回加密方式(*)
                    "<RetType>" + "1" + "</RetType>" +//是否提供Server返回方式(*)
                    "<ServerUrl><![CDATA[" + "http://43.227.216.84/PayResulthxzfyl.do" + "]]></ServerUrl>" +//商户S2S返回地址(*)
                    "<BillEXP>" + "24" + "</BillEXP>" +//订单有效期(小时为单位)
                    "<GoodsName>" + body + "</GoodsName>" +//商品名称
                    "<IsCredit>" + "" + "</IsCredit>" +//直连支付方式(*) 默认非直连 不用传值
                    "<BankCode>" + "" + "</BankCode>" +//直连银行号（网关号）非直连 不用传值
                    "<ProductType>" + "" + "</ProductType>" +//直连个/企选择 非直连 不用传值
                    "</body>";
            // MD5签名
            String directStr = map.get("directStr");
            String sign = DigestUtils
                    .md5Hex(Verify.getBytes(bodyXml + "208072" + directStr,
                            "UTF-8"));
            // xml
            String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String xml = "<Ips>" +
                    "<GateWayReq>" +
                    "<head>" +
                    "<Version>" + "v1.0.0" + "</Version>" +//版本号
                    "<MerCode>" + "208072" + "</MerCode>" +//商户号(*)
                    "<MerName>" + "测试商户" + "</MerName>" +//商户名称(*)
                    "<Account>" + "2080720010" + "</Account>" +//商户账户号(*)
                    "<MsgId>" + "msg" + date + "</MsgId >" +
                    "<ReqDate>" + date + "</ReqDate >" +
                    "<Signature>" + sign + "</Signature>" +
                    "</head>" +
                    bodyXml +
                    "</GateWayReq>" +
                    "</Ips>";
            System.out.println(">>>>> 订单支付 请求信息: " + xml);
            request.setAttribute("action", action);
            request.setAttribute("pGateWayReq", xml);
            //request.getRequestDispatcher("WEB-INF/views/sinopayPaymentForm.jsp").forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "pay/sinopayPaymentForm";
    }
}